function mi = MI(a,b)
%Caculate MI of a and b in the region of the overlap part

%calculate the overlaped area
[Ma,Na] = size(a);
[Mb,Nb] = size(b);
M=min(Ma,Mb);
N=min(Na,Nb);

%initialize the histogram.
hab = zeros(32,32);
ha = zeros(1,32);
hb = zeros(1,32);

%normalize
a = mat2gray(a);
b = mat2gray(b);

a = double(int16(a*255));
b = double(int16(b*255));

%calculate the histogram
for i=1:M
    for j=1:N
       indexx = floor(a(i,j)/8) + 1;
       indexy = floor(b(i,j)/8) + 1;
       hab(indexx,indexy) = hab(indexx,indexy)+1;%jiont histogram
       ha(indexx) = ha(indexx)+1; 
       hb(indexy) = hb(indexy)+1;
   end
end

%hab = mat2gray(hab);
%hab = log(hab) ./ log(1024);
%imwrite(hab,'hab.bmp','bmp');
%imshow(hab);

%calculate the joint entropy 
hsum = sum(sum(hab));
index = find(hab~=0);
p = hab/hsum;
Hab = sum(sum(-p(index).*log(p(index))));

%calculate the entropy of a
hsum = sum(sum(ha));
index = find(ha~=0);
p = ha/hsum;
Ha = sum(sum(-p(index).*log(p(index))));

%calculate the entropy of b
hsum = sum(sum(hb));
index = find(hb~=0);
p = hb/hsum;
Hb = sum(sum(-p(index).*log(p(index))));

%calculate the MI of a and b
mi = Ha+Hb-Hab;

%calulate the normalized MI
%mi = hab/(Ha+Hb);